package com.fesine.crm.controller;

import com.fesine.commons.entity.Result;
import com.fesine.commons.enums.ResultEnum;
import com.fesine.commons.util.CryptographyUtil;
import com.fesine.commons.util.ResultUtils;
import com.fesine.crm.dto.SysUserDto;
import com.fesine.crm.exception.CrmException;
import com.fesine.crm.po.EmployeeInfoPo;
import com.fesine.crm.po.SysUserPo;
import com.fesine.crm.service.EmployeeInfoService;
import com.fesine.crm.service.SysUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2017/10/10 23:15
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/10/10 23:15
 */
@RestController
@RequestMapping("/v1")
public class SysUserController {
    private final static Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    SysUserService service;

    @Autowired
    EmployeeInfoService empService;

    @ApiOperation(value = "登录系统", httpMethod = "POST", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pacteraNo", required = true, dataType = "String",
                    paramType = "body"),
            @ApiImplicitParam(name = "password", required = true, dataType = "String",
                    paramType = "body")
    })
    @PostMapping("/user/login")
    public Result login(HttpServletRequest request, EmployeeInfoPo po) {
        Map<String, Object> map = new HashMap<>();
        String captchaToken = ((String) request.getSession().getAttribute("captchaToken"))
                .toLowerCase();
        String checkCode = request.getParameter("checkCode").toLowerCase();
        logger.info("----->captchaToken:" + captchaToken + ",checkCode:" + checkCode);
        //不区分大小写
        if (!captchaToken.equals(checkCode.toLowerCase())) {
            return ResultUtils.error(405, "验证码错误!");
        }
        //验证公司号和密码
        String pacteraNo = po.getPacteraNo();
        EmployeeInfoPo poTemp = new EmployeeInfoPo();
        poTemp.setPacteraNo(pacteraNo.toUpperCase());
        poTemp.setPassword(CryptographyUtil.md5(po.getPassword(), "fesine"));
        poTemp = empService.get(poTemp);
        if (poTemp == null) {
            return ResultUtils.error(405, "用户名或密码错误!");
        }
        //用户登录成功后，会判断管理员权限
        SysUserPo userPo = new SysUserPo();
        userPo.setPacteraNo(pacteraNo);
        userPo = service.get(userPo);
        //添加管理员级别
        if (userPo != null) {
            request.getSession().setAttribute("grade", userPo.getGrade());
            map.put("grade", userPo.getGrade());
        } else {
            //普通用户
            request.getSession().setAttribute("grade", 0);
            map.put("grade", 0);
        }
        request.getSession().setAttribute("pacteraNo", po.getPacteraNo());
        request.getSession().setAttribute("name", poTemp.getName());
        map.put("user", poTemp);
        return ResultUtils.success(map);
    }

    @ApiOperation(value = "注销系统", httpMethod = "GET", response = Result.class)
    @GetMapping("/user/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return ResultUtils.success();
    }

    @GetMapping("/users")
    public Result list(SysUserPo po) {
        List<SysUserDto> list = service.listDto(po);
        return ResultUtils.success(list);
    }

    @GetMapping("/user/{id}")
    public Result get(@PathVariable("id") Integer id) {
        Map<String, Object> map = new HashMap<>();
        SysUserPo po = new SysUserPo();
        po.setId(id);
        po = service.get(po);
        if (po != null) {
            EmployeeInfoPo empPo = new EmployeeInfoPo();
            empPo.setPacteraNo(po.getPacteraNo());
            empPo = empService.get(empPo);
            if (empPo != null) {
                map.put("user", po);
                map.put("emp", empPo);
            }
        }
        return ResultUtils.success(map);
    }

    /**
     * 添加管理员信息
     *
     * @param po
     * @return
     */
    @PostMapping("/user")
    public Result save(SysUserPo po) {
        int i = service.save(po);
        if (i == 1) {
            return ResultUtils.success(ResultEnum.CREATED,po);
        }
        throw new CrmException(ResultEnum.INVALID_REQUEST);
    }

    /**
     * 修改管理员信息
     *
     * @param po
     * @return
     */
    @PutMapping("/user/{id}")
    public Result update(@PathVariable Integer id,SysUserPo po) {
        int i = service.update(po);
        if (i == 1) {
            return ResultUtils.success(ResultEnum.CREATED,po);
        }
        throw new CrmException(ResultEnum.INVALID_REQUEST);
    }


    /**
     * 删除管理员信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/user/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        SysUserPo po = new SysUserPo();
        po.setId(id);
        int i = service.delete(po);
        if (i == 1) {
            return ResultUtils.success(ResultEnum.DELETED,id);
        }
        throw new CrmException(ResultEnum.INVALID_REQUEST);
    }

    @DeleteMapping("/users/{ids}")
    public Result deleteInfos(@PathVariable String ids) {
        String[] idsArr = ids.split(",");
        SysUserPo po;
        try {
            for (String s : idsArr) {
                po = new SysUserPo();
                po.setId(Integer.parseInt(s));
                service.delete(po);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new CrmException(ResultEnum.INVALID_REQUEST);
        }
        return ResultUtils.success(ResultEnum.DELETED, ids);
    }
}
